<template>
  <div class="selectQuestion">
    <div class="container">
      <div class="selectionTop">
        <div class="selectionTopLeft">
          <h1>{{ questionmanage }}管理</h1>
          <div
            class="questionData"
            v-if="topicType == 0"
          >
            <p>
              <span>题目数量：
                <span
                  v-if="operateType == 'edit'">{{ editQuestionCount }}</span>
                <span
                  v-if="operateType == 'add'">{{ dictStore.singleChoiceIds.length?dictStore.singleChoiceIds.length:0 }}</span>
              </span>
            </p>

            <p>总分值：
              {{ questionCount * questionScore }}
            </p>
          </div>

          <div
            class="questionData"
            v-if="topicType == 1"
          >
            <p>
              应选题目数量：
              {{ questionCount }}

            </p>
            <p>总分值：
              {{ dictStore.multipleChoiceIds.length * questionScore}}
              {{ questionCount * questionScore }}
            </p>
          </div>
          <div
            class="questionData"
            v-if="topicType == 2"
          >
            <p>
              应选题目数量：
              {{ questionCount }}
            </p>
            <p>总分值：
              {{ questionCount * questionScore }}
            </p>
          </div>
          <div
            class="questionData"
            v-if="topicType == 3"
          >
            <p>
              应选题目数量：
              {{ questionCount }}
            </p>
            <p>总分值：
              {{ questionCount * questionScore}}
            </p>
          </div>
          <div
            class="questionData"
            v-if="topicType == 4"
          >
            <p>
              应选题目数量：
              {{ questionCount }}
            </p>
            <p>总分值：
              {{ questionCount * questionScore}}
            </p>
          </div>
        </div>

        <div class="selectionTopRight">
          <el-button
            plain
            class="backBtn"
            @click="backBtn"
          >返回</el-button>
        </div>
      </div>

      <div class="selectionTable">
        <div class="choiceType">
          选题方式：
          <el-radio-group
            v-model="selectionType"
            class="ml-4"
            @change="getAccordQuestionList1"
          >
            <el-radio
              label="autoSelection"
              size="large"
            >自动选择</el-radio>
            <el-radio
              label="manualSelection"
              size="large"
              style="margin-left: 120px;"
            >手动选择</el-radio>
          </el-radio-group>
        </div>

        <div class="searchQuestion">
          <span>题目名称：</span>
          <el-input
            style="width: 256px;"
            clearable
            v-model="searchQuestion"
            @clear="getAccordQuestionList"
          >
            <template #suffix>
              <el-icon
                class="el-input__icon"
                style="cursor: pointer;"
                @click="getAccordQuestionList"
              >
                <search />
              </el-icon>
            </template>
          </el-input>

          <img
            src="@/assets/images/reset.png"
            style="margin-left: 36px;margin-right: 8px;cursor: pointer;"
            @click="resetSearchData"
          >
          <p
            style="cursor: pointer;"
            @click="resetSearchData"
          >重置数据</p>

        </div>

        <div class="tableData">
          <el-table
            :data="tableData"
            @selection-change="selectQuestion"
            :row-key="getRowKeys"
            @select-all="handleSelectAll"
            style="width: 100%;"
            ref="questionTable"
          >
            <el-table-column
              type="selection"
              width="79"
              :selectable="rowSelectable"
              :reserve-selection="true"
              v-if="selectionType=='manualSelection'"
            />
            <el-table-column
              prop="id"
              label="ID"
              width="80"
            />
            <el-table-column
              prop="topic"
              label="题目"
              width="244"
            />
            <el-table-column
              prop="optionA"
              label="选项A"
              v-if="topicType == '0' || topicType == '1' || topicType == '2'"
            />
            <el-table-column
              prop="optionB"
              label="选项B"
              v-if="topicType == '0' || topicType == '1' || topicType == '2'"
            />
            <el-table-column
              prop="optionC"
              label="选项C"
              v-if="topicType == '0' || topicType == '1'"
            />
            <el-table-column
              prop="optionD"
              label="选项D"
              v-if="topicType == '0' || topicType == '1'"
            />
            <el-table-column
              prop="optionE"
              label="选项E"
              v-if="topicType == '1'"
            />
            <el-table-column
              prop="optionF"
              label="选项F"
              v-if="topicType == '1'"
            />
            <el-table-column
              v-if="topicType !== '1'"
              prop="rightAnswers"
              label="答案"
            />
            <el-table-column
              v-if="topicType == '1'"
              prop="rightAnswersMore"
              label="答案"
            />

          </el-table>
        </div>

        <div class="pagination">
          <Pagination
            :limit="paginationData.pageSize"
            :page="paginationData.pageNum"
            :total="paginationData.total"
            @pagination="handlePagination"
          ></Pagination>
        </div>

        <div class="cancelAndSave">
          <el-button
            plain
            class="cancelBtn"
            @click="cancelBtn"
          >取消</el-button>
          <el-button
            plain
            class="saveBtn"
            @click="saveChoice"
          >保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import Pagination from './../../../../components/Pagination/index.vue'
import { computed, nextTick, onMounted, onUnmounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

// 引入存储id的pinia仓库
import { useDictStore } from '@/store/modules/addtest.js'

// 引入当前编辑的试卷所拥有的题目
import { useTestpaperDetailStore } from '@/store/modules/testpaperdetail.js'

const dictStore = useDictStore()

const testpaperDetailStore = useTestpaperDetailStore()




// 引入查询题库列表的接口
import { getQuestionList } from '@/api/assessment/questionmanage.js'

// 引入随机获取单项试题的接口
import { getRandomQuestion } from '@/api/assessment/testpapermanage.js'
import { ElMessage } from 'element-plus';
import { get } from '@vueuse/core';
const route = useRoute()
const router = useRouter()

const questionmanage = computed(() => {
  if (route.query.type == 0) {
    return '单选题'
  } else if (route.query.type == 1) {
    return '多选题'
  } else if (route.query.type == 2) {
    return '判断题'
  } else if (route.query.type == 3) {
    return '填空题'
  } else if (route.query.type == 4) {
    return '论述题'
  }
})
const topicType = computed(() => Number(route.query.type))

// 问题类型
const operateType = computed(() => route.query.operateType)

// 问题数量
const questionCount = computed(() => route.query.questionCount)

// 问题分值
const questionScore = computed(() => route.query.questionScore)

// 选题方式
const selectionType = ref('manualSelection')

const searchQuestion = ref('')


// 定义表格数据
const tableData = ref([])

// 定义分页数据
const paginationData = ref({
  pageNum: 1,
  pageSize: 10
})
const editQuestionCount = ref(0)
let timer1 = setTimeout(() => {
  paginationData.value.pageSize = 10
  getAccordQuestionList()
  if (topicType.value == 0) {
    editQuestionCount.value = dictStore.singleChoiceIds.length
  } else if (topicType.value == 1) {
    editQuestionCount.value = dictStore.multipleChoiceIds.length
  } else if (topicType.value == 2) {
    editQuestionCount.value = dictStore.judgmentIds.length
  } else if (topicType.value == 3) {
    editQuestionCount.value = dictStore.fillInTheBlanksIds.length
  } else if (topicType.value == 4) {
    editQuestionCount.value = dictStore.discussChoiceIds.length
  }
}, 300)
onUnmounted(() => {
  clearTimeout(timer1)
})

// 根据路由参数，查询当前选择的问题的题库
async function getAccordQuestionList () {
  const res = await getQuestionList({
    topicType: topicType.value,
    sourceType: 0,
    searchValue: searchQuestion.value,
    ...paginationData.value
  })
  console.log(res)
  paginationData.value.total = res.total
  tableData.value = res.rows
}

// 处理分页
function handlePagination (val) {
  console.log(val)
  paginationData.value.pageSize = val.limit
  paginationData.value.pageNum = val.page
  getAccordQuestionList()
}

function resetSearchData () {
  searchQuestion.value = ''
  getAccordQuestionList()
}

const questionData = ref([])

// 当路由路径发生变化，就调用函数
onMounted(() => {
  getAccordQuestionList()
  if (topicType.value == 0) {
    questionData.value = dictStore.singleChoiceIds
  } else if (topicType.value == 1) {
    questionData.value = dictStore.multipleChoiceIds
  } else if (topicType.value == 2) {
    questionData.value = dictStore.judgeChoiceIds
  } else if (topicType.value == 3) {
    questionData.value = dictStore.fillChoiceIds
  } else if (topicType.value == 4) {
    questionData.value = dictStore.discussChoiceIds
  }
  console.log(questionData.value)
})

const singleChoiceIds = ref([])
const multipleChoiceIds = ref([])
const judgeChoiceIds = ref([])
const fillChoiceIds = ref([])
const discussChoiceIds = ref([])
const idss = ref([])

const questionCounts = ref(0)
const selectQuestionData = ref([])
function getRowKeys (row) {
  return row.id
}

function selectQuestion (item) {
  console.log(item)

  questionCounts.value = item.length

  if (item.length > questionCount.value) {
    return ElMessage.error('题目数量不能超过' + questionCount.value)
  } else {
    const ids = item.map(item => item.id)
    idss.value = ids
    if (topicType.value == 0) {
      dictStore.addSingleChoiceId(ids)
    }
    else if (topicType.value == 1) {
      dictStore.addMultipleChoiceId(ids)
    }
    else if (topicType.value == 2) {
      dictStore.addJudgeChoiceId(ids)
    }
    else if (topicType.value == 3) {
      dictStore.addFillChoiceId(ids)
    }
    else if (topicType.value == 4) {
      dictStore.addDiscussChoiceId(ids)
    }
  }
  console.log(dictStore.fillChoiceIds)
}

// 自动选择
async function autoSelect () {
  if (selectionType.value == 'autoSelection') {
    const res = await getRandomQuestion({
      randomNumber: questionCount.value,
      topicType: topicType.value,
      sourceType: 0
    })
  }
}
autoSelect()

watch(
  selectionType,
  async (newValue, oldValue) => {
    if (newValue == 'autoSelection') {
      const res = await getRandomQuestion({
        randomNumber: questionCount.value,
        topicType: topicType.value,
        sourceType: 0,
        pageNum: 1,
        pageSize: 10,
      })
      const ids = res.data.map(item => item.id)
      idss.value = ids
      tableData.value = res.data
      if (topicType.value == 0) {
        dictStore.addSingleChoiceId(ids)

      }
      else if (topicType.value == 1) {
        dictStore.addMultipleChoiceId(ids)

      }
      else if (topicType.value == 2) {
        dictStore.addJudgeChoiceId(ids)

      }
      else if (topicType.value == 3) {
        dictStore.addFillChoiceId(ids)

      }
      else if (topicType.value == 4) {
        dictStore.addDiscussChoiceId(ids)

      }
    } else if (newValue == 'manualSelection') {
      idss.value = []
      getAccordQuestionList()
    }
  },
  {
    immediate: true,
    deep: true
  }
)

function rowSelectable (row) {
  if (idss.value.length == questionCount.value && !idss.value.includes(row.id)) {
    return false
  }
  return true
}

function getAccordQuestionList1 (item) {
  if (item == 'manualSelection') {
    if (questionmanage.value == '单选题') {
      dictStore.clearSingleChoiceId()
    } else if (questionmanage.value == '多选题') {
      dictStore.clearMultipleChoiceId()
    } else if (questionmanage.value == '判断题') {
      dictStore.clearJudgeChoiceId()
    } else if (questionmanage.value == '填空题') {
      dictStore.clearFillChoiceId()
    } else if (questionmanage.value == '简答题') {
      dictStore.clearDiscussChoiceId()
    }
    ElMessage({
      message: '您已切换选题方式，请重新选择题目！'
    })
  }
}

const questionTable = ref(null)
// 全选数量超过就禁用
function handleSelectAll (row) {
  console.log(questionTable.value.data.length)
  let allSelectResult = questionTable.value.data.length
  if (allSelectResult > questionCount.value) {
    ElMessage({
      message: '超出最大数量限制',
      type: 'info'
    })
    return
  }
}



let timer = 0;
function questionEcho () {
  timer = setTimeout(() => {
    if (operateType.value == 'edit') {
      if (topicType.value == 0) {
        let singleChoiceIds = dictStore.singleChoiceIds
        tableData.value.forEach(item => {
          questionData.value.forEach(item2 => {
            if (item.id == item2) {
              questionTable.value.toggleRowSelection(item, true)
            }
          })
        })
      } else if (topicType.value == 1) {
        let multipleChoiceIds = dictStore.multipleChoiceIds
        tableData.value.forEach(item => {
          questionData.value.forEach(item2 => {
            if (item.id == item2) {
              questionTable.value.toggleRowSelection(item, true)
            }
          })
        })
      } else if (topicType.value == 2) {
        let judgeChoiceIds = dictStore.judgeChoiceIds
        tableData.value.forEach(item => {
          questionData.value.forEach(item2 => {
            if (item.id == item2) {
              questionTable.value.toggleRowSelection(item, true)
            }
          })
        })
      } else if (topicType.value == 3) {
        let fillChoiceIds = dictStore.fillChoiceIds
        tableData.value.forEach(item => {
          questionData.value.forEach(item2 => {
            if (item.id == item2) {
              questionTable.value.toggleRowSelection(item, true)
            }
          })
        })
      } else if (topicType.value == 4) {
        let discussChoiceIds = dictStore.discussChoiceIds
        tableData.value.forEach(item => {
          questionData.value.forEach(item2 => {
            if (item.id == item2) {
              questionTable.value.toggleRowSelection(item, true)
            }
          })
        })
      }
    } else if (operateType.value == 'add') {
      if (topicType.value == 0) {
        let singleChoiceIds = dictStore.singleChoiceIds
        tableData.value.forEach(item => {
          questionData.value.forEach(item2 => {
            if (item.id == item2) {
              questionTable.value.toggleRowSelection(item, true)
            }
          })
        })
      } else if (topicType.value == 1) {
        let multipleChoiceIds = dictStore.multipleChoiceIds
        tableData.value.forEach(item => {
          questionData.value.forEach(item2 => {
            if (item.id == item2) {
              questionTable.value.toggleRowSelection(item, true)
            }
          })
        })
      } else if (topicType.value == 2) {
        let judgeChoiceIds = dictStore.judgeChoiceIds
        tableData.value.forEach(item => {
          questionData.value.forEach(item2 => {
            if (item.id == item2) {
              questionTable.value.toggleRowSelection(item, true)
            }
          })
        })
      } else if (topicType.value == 3) {
        let fillChoiceIds = dictStore.fillChoiceIds
        tableData.value.forEach(item => {
          questionData.value.forEach(item2 => {
            if (item.id == item2) {
              questionTable.value.toggleRowSelection(item, true)
            }
          })
        })
      } else if (topicType.value == 4) {
        let discussChoiceIds = dictStore.discussChoiceIds
        tableData.value.forEach(item => {
          questionData.value.forEach(item2 => {
            if (item.id == item2) {
              questionTable.value.toggleRowSelection(item, true)
            }
          })
        })
      }
    }

  }, 500)
}
questionEcho()

watch(
  () => tableData.value,
  (newVal, oldVal) => {
    if (newVal[0]?.id != oldVal[0]?.id) {
      questionEcho()
    }

  },
  {
    deep: true,
  }
)

// 清除定时器
onBeforeUnmount(() => {
  clearTimeout(timer)
})






const selectBox = ref(true)
watch(idss, (newValue, oldValue) => {
  if (newValue.length > questionCount.value) {
    selectBox.value = false
  }
}, {
  immediate: true,
  deep: true
})

function saveChoice () {

  if (selectionType.value == 'autoSelection') {
    ElMessage({
      type: 'success',
      message: '自动选题成功'
    })
    router.push({
      path: 'addtestpaper',
      query: {
        type: 'edit',
        isGetData: 0
      }
    })
  } else if (selectionType.value == 'manualSelection') {
    if (questionCounts.value > questionCount.value) {
      ElMessage({
        type: 'error',
        message: '选题数量不能大于设置题目数量'
      })
    } else if (questionCounts.value <= 0) {
      ElMessage({
        type: 'info',
        message: '当前未选择题目，您可以选择返回上一页或取消选题'
      })
    } else if (questionCounts.value < questionCount.value) {
      return ElMessage({
        type: 'info',
        message: '当前选择题目数量小于预设题目数量，请检查'
      })
    } else {
      ElMessage({
        type: 'success',
        message: '手动选题成功'
      })
      router.push({
        path: 'addtestpaper',
        query: {
          type: 'edit',
          isGetData: 0
        }
      })
    }
  }

  console.log(dictStore.fillChoiceIds)
}



// 返回按钮
function backBtn () {
  router.go(-1)
}

function cancelBtn () {
  router.go(-1)

}




</script>

<style lang='scss' scoped>
.selectQuestion {
  padding: 32px;
  background-color: #f5f6f9;
  .container {
    min-height: 936px;
    background: #ffffff;
    border-radius: 10px 10px 10px 10px;
    padding-bottom: 20px;
    .selectionTop {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 88px;
      padding: 0 32px 0 40px;
      border-bottom: 1px solid #d4d4d4;
      .selectionTopLeft {
        width: 500px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        h1 {
          font-size: 22px;
          color: #343957;
        }

        p {
          font-size: 16px;
          color: #343957;
        }
        .questionData {
          display: flex;
          justify-content: space-between;
          width: 260px;
        }
      }
      .selectionTopRight {
        .backBtn {
          width: 80px;
          height: 40px;
          border-radius: 6px 6px 6px 6px;
          border: 1px solid #5974ff;
          font-size: 16px;
          color: #5974ff;
        }
      }
    }

    .selectionTable {
      padding: 24px 32px 0 32px;
      .searchQuestion {
        display: flex;
        align-items: center;
        margin-top: 25px;
      }

      .tableData {
        margin-top: 24px;
        ::v-deep(.el-table__header) {
          height: 56px;
        }

        ::v-deep(.el-table__row) {
          height: 56px;
        }
      }

      .cancelAndSave {
        display: flex;
        justify-content: end;
        margin-top: 38px;
        .cancelBtn {
          width: 108px;
          height: 40px;
          border-radius: 6px 6px 6px 6px;
          border: 1px solid #5974ff;
          font-size: 16px;
          color: #5974ff;
        }

        .saveBtn {
          width: 108px;
          height: 40px;
          background: #5974ff;
          border-radius: 6px 6px 6px 6px;
          font-size: 16px;
          color: #ffffff;
        }
      }
    }
  }
}
</style>
